<!-- src/components/ReplyForm.vue -->
<template>
  <div class="reply-form">
    <el-form
      :model="replyForm"
      :rules="replyRules"
      ref="replyFormRef"
      label-width="0px"
    >
      <el-form-item prop="content">
        <el-input
          v-model="replyForm.content"
          type="textarea"
          :rows="3"
          :placeholder="placeholderText"
          maxlength="1000"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitReply" :loading="loading" size="small">提交评论</el-button>
        <el-button @click="cancelReply" size="small" v-if="showCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { createReply } from '@/services/replyService'; // 引入真实的回复服务

const props = defineProps({
  postId: { type: Number, required: true },
  parentId: { type: Number, default: null },
  showCancel: { type: Boolean, default: false },
  initialContent: { type: String, default: '' }
});

const emit = defineEmits(['replySubmitted', 'replyCancelled']);

const replyFormRef = ref();
const loading = ref(false);

const replyForm = reactive({ content: props.initialContent });

watch(() => props.initialContent, (newVal) => {
  replyForm.content = newVal;
}, { immediate: true });

const placeholderText = computed(() => {
  return props.initialContent ? '编辑回复内容...' : '请输入回复内容...';
});

const replyRules = {
  content: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 1, max: 1000, message: '回复内容长度为 1 到 1000 个字符', trigger: 'blur' }
  ]
};

const submitReply = async () => {
  if (!replyFormRef.value) return;
  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // --- 使用真实的 API ---
        const response = await createReply({
          content: replyForm.content,
          postId: props.postId,
          parentId: props.parentId // 如果是顶级回复，parentId 为 null
        });
        console.log('Real Reply created:', response.data);
        ElMessage.success('回复成功');
        // 将后端返回的完整回复对象 emit 给父组件
        emit('replySubmitted', response.data);
        if (!props.initialContent) { // Only clear if it wasn't pre-filled for editing
            replyForm.content = ''; // Clear form only for new replies
        }
        //replyForm.content = ''; // 清空表单
        // --- ---
      } catch (error) {
        console.error('Submit reply failed:', error);
        // 显示后端返回的错误信息或默认信息
        ElMessage.error(error.response?.data?.message || '回复失败');
      } finally {
        loading.value = false;
      }
    } else {
      console.log('Reply form validation failed!');
      return false;
    }
  });
};

const cancelReply = () => {
  emit('replyCancelled');
};
</script>

<style scoped>
.reply-form {
  margin-top: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}
</style>
